import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_quick_menu.dart';
import 'package:qunaimedical/components/item_qa_doctor.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/qa_doctor.dart';
import 'package:qunaimedical/models/qa_user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/doctor_list.dart';
import 'package:qunaimedical/pages/login.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/utils/auth_util.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/event_bus_manager.dart';
import 'package:qunaimedical/utils/navigator_util.dart';
import 'package:qunaimedical/values/configs.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:provider/provider.dart';


class SummaryPage extends StatefulWidget {
  @override
  _SummaryPageState createState() => _SummaryPageState();
}

class _SummaryPageState extends State<SummaryPage> {
  final List<String> _gridImages = [
    'assets/images/ic_qa_add_meet.png',
    'assets/images/ic_qa_meet_list.png',
    'assets/images/ic_qa_my_meet.png',
    'assets/images/ic_qa_meets.png',
    'assets/images/ic_qa_msg.png',
    'assets/images/ic_qa_news.png',
    'assets/images/ic_qa_data.png',
    'assets/images/ic_qa_user_list.png',
  ];

  final List<String> _gridTitles = [
    '预约会诊',
    '会诊大厅',
    '我的会诊',
    '往期会议',
    '新手教程',
    '群爱资讯',
    '学术专栏',
    '专家',
  ];

  List<QADoctor> _doctorList = [];

  @override
  void initState() {
    super.initState();
    _fetchDoctorList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        toolbarHeight: 80,
        title: _buildLeadingWidget(),
        actions: [
          IconButton(
            onPressed: () =>
                toMyConsultation(context, MyConsultationType.myreceive),
            icon: Icon(
              Icons.today_outlined,
              color: Colors.white,
            ),
          ),
          IconButton(
            onPressed: () {
              eventBus.fire(EventBusMessage.jump2Conversations);
            },
            icon: Icon(
              Icons.notifications_none,
              color: Colors.white,
            ),
          ),
        ],
      ),
      body: CustomScrollView(
        slivers: [
          SliverGrid(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int position) {
                final title = _gridTitles[position];
                return ItemQuickMenu(
                  imagePath: _gridImages[position],
                  text: title,
                  onTap: () async {
                    final urls = [
                      Urls.BOOK_A_CONSULTATION,
                      Urls.CONSULTATION_CENTER,
                      Urls.CONSULTATIONS,
                      Urls.HISTORY,
                      Urls.TUTORIAL,
                      Urls.NEWS,
                      Urls.DATAS,
                      Urls.DOCTORS,
                    ];
                    String url = urls[position];
                    if (position == 2) {
                      url += "?reqfrom=app&handle=myreceive";
                    }

                    pushTo(
                      context,
                      WebPage(
                        url: url,
                        title: title,
                      ),
                      authStateRequired: true,
                    );
                  },
                );
              },
              childCount: _gridImages.length,
            ),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              childAspectRatio:
                  MediaQuery.of(context).size.width > 600 ? 2 : 1.1,
            ),
          ),
          SliverToBoxAdapter(child: CustomDivider()),
          _buildDoctorList(),
        ],
      ),
    );
  }

  /// 医生列表
  Widget _buildDoctorList() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          if (index == 0) {
            return Container(
              height: 60,
              child: PrimaryLabel(
                '群爱名医',
                trailing: InkWell(
                  child: Row(
                    children: [
                      Text(
                        '更多',
                        style: TextStyle(fontSize: 16, color: Colors.grey),
                      ),
                      Icon(
                        CupertinoIcons.right_chevron,
                        color: Colors.grey,
                        size: 18,
                      )
                    ],
                  ),
                  onTap: () {
                    pushTo(context, DoctorListPage());
                  },
                ),
              ),
            );
          }
          return QAItemDoctor(_doctorList[index - 1]);
        },
        childCount: _doctorList.length + 1,
      ),
    );
  }

  void _fetchDoctorList() async {
    try {
      Response response = await XHttp.instance.get(Urls.DOCTOR_LIST);
      if (mounted) {
        if (response.statusCode == 200 && response.data != null) {
          List list = response.data as List;
          List<QADoctor> data =
              List<QADoctor>.from(list.map((i) => QADoctor.fromJson(i)));
          if (mounted) {
            setState(() {
              _doctorList.clear();
              _doctorList.addAll(data);
            });
          }
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        CommonUtil.catchDioError(e);
      }
    }
  }

  Widget _buildLeadingWidget() {
    QAUser? user = context.watch<StoreInfo>().qaUser;
    return InkWell(
      child: Text(AuthUtil.isLogin()
          ? user!.name + "${_getUserDisplayType(user.usertype)}，您好！"
          : "您好，请先登录"),
      onTap: AuthUtil.isLogin() ? null : () => pushTo(context, LoginPage()),
    );
  }

  String _getUserDisplayType(String? value) {
    if (value == null || value == "") {
      return "";
    }
    if (value == UserType.doctor.name) {
      return "医生";
    } else {
      return "医助";
    }
  }
}
